//
//  invoiceViewController.m
//  ZPSALE
//
//  Created by tmosport on 14-6-30.
//  Copyright (c) 2014年 tmosport. All rights reserved.
//

#import "invoiceViewController.h"
#import "creatOrderViewController.h"
#import "MBProgressHUD.h"

@interface invoiceViewController ()
@property(nonatomic,strong)NSArray *invoiceList;

@property(nonatomic,strong)NSString *itemTitle;
@property(nonatomic,strong)NSString *typeTitle;
@property(nonatomic,retain)NSIndexPath* lastIndex0;
@property(nonatomic,retain)NSIndexPath* lastIndex1;
@property(nonatomic,retain)NSMutableDictionary *invoiceInfo;


@end

@implementation invoiceViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"请选择发票类型";
    [self setNavigationItem];
    self.navigationItem.rightBarButtonItem =[[UIBarButtonItem alloc]
                                             initWithTitle:@"保存"
                                             style:UIBarButtonItemStyleBordered
                                             target:self
                                             action:@selector(toSave)];
    // Do any additional setup after loading the view.
    [self dataInit];
    _invoiceTitle = @"发票抬头";
    _invoiceItem = @"";
    _invoiceType = @"3";
    _typeTitle = @"不开发票";
    _invoiceTitle = @"";
    _lastIndex0 = [NSIndexPath indexPathForRow:0 inSection:0];
    _lastIndex1 = [NSIndexPath indexPathForRow:0 inSection:0];
    _invoiceInfo = [NSMutableDictionary dictionaryWithObjectsAndKeys:_invoiceType,@"invoiceType",_typeTitle, @"typeTitle",_invoiceTitle,@"invocieTitle",_invoiceItem, @"invocieItem",_itemTitle, @"itemTitle",nil];
}

-(void)setNavigationItem {
    [self.navigationController.navigationBar setBackIndicatorImage:
     [UIImage imageNamed:@"return"]];
    [self.navigationController.navigationBar setBackIndicatorTransitionMaskImage:
     [UIImage imageNamed:@"return"]];
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStyleBordered target:nil action:nil];
}

-(void)leftBarbuttonItemClicked:(UIButton *)button {
    [self.navigationController popViewControllerAnimated:YES];
}


-(void)toSave
{
    if ([_invoiceType length] == 0 ||[_invoiceType isEqual:[NSNull null]] ) {
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"保存失败" message:@"请选择发票类型" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alertView show];
        return;
    }
    if ([_invoiceType intValue] == 1) {
        //判断个人发票类型
        if ([_invoiceType length] == 0 ||[_invoiceType isEqual:[NSNull null]] ||[_invoiceItem length] == 0 ||[_invoiceItem isEqual:[NSNull null]]) {
            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"保存失败" message:@"请正确选择发票明细" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
            [alertView show];
            return;
        }
    }
    if ([_invoiceType intValue] == 2) {
        //判断公司发票类型
        if ([_invoiceType length] == 0 ||[_invoiceType isEqual:[NSNull null]] ||[_invoiceItem length] == 0 ||[_invoiceItem isEqual:[NSNull null]]||[_invoiceTitle length] == 0 ||[_invoiceTitle isEqual:[NSNull null]]) {
            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"保存失败" message:@"请填写抬头并选择发票明细" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
            [alertView show];
            return;
        }
    }
    if ([_invoiceType intValue] == 3) {
        //判断公司发票类型
        if ([_invoiceType length] == 0 ||[_invoiceType isEqual:[NSNull null]] ) {
            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"保存失败" message:@"请正确填写发票信息" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
            [alertView show];
            return;
        }
    }
    [[NSNotificationCenter defaultCenter] postNotificationName:@"changeInvoiceInfo" object:_invoiceInfo];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)dataInit{
    MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    HUD.dimBackground = NO;
    HUD.labelText = @"获取数据中";
    NSDictionary *params = @{@"memberid": _memberId,
                             @"access_token": _token,
                             };
    AFHTTPRequestOperationManager *manger = [AFHTTPRequestOperationManager manager];
    [manger POST:APIURL@"orders/getOrderExtensionInfo.json" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        _invoiceList = responseObject[@"orderExtensionInfo"][@"invoiceItem"];
        [self.invoiceTV reloadData];
        [HUD hide:YES];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        //DO:错误捕获
        [HUD hide:YES afterDelay:1];
    }];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0 ) {
        return 3;
    }else{
        return [_invoiceList count];
    }
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    
    NSString *titleForHeader;
    //    UIFont *font = [UIFont fontWithName:@"Heiti SC" size:15];
    
    if (section == 0) {
        titleForHeader =  @"发票类型";
    }else{
        titleForHeader =  @"发票明细";
    }
    return titleForHeader;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 26.0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    NSString *sectionTitle=[self tableView:tableView titleForHeaderInSection:section];
    if (sectionTitle==nil) {
        return nil;
    }

    UIFont *font = [UIFont fontWithName:@"Heiti SC" size:15];
    // Create label with section title
    UILabel *label=[[UILabel alloc] initWithFrame:CGRectMake(14, 0, 300, 22)];
    label.backgroundColor=[UIColor clearColor];
    label.font=font;
    label.text=sectionTitle;
    
    // Create header view and add label as a subview
    UIView *sectionView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 20)] ;
    [sectionView setBackgroundColor:[UIColor clearColor]];
    [sectionView addSubview:label];
    return sectionView;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell;
    UIFont *font = [UIFont fontWithName:@"Heiti SC" size:15];
    if (indexPath.section == 0 ) {

        NSArray *typeString = [NSArray arrayWithObjects:@"不开发票",@"个人",nil];

        if (indexPath.row < 2) {
            cell = nil;
            cell = [tableView dequeueReusableCellWithIdentifier:@"reuseCell"];
            cell.textLabel.text = [NSString stringWithFormat:@"%@",[typeString objectAtIndex:indexPath.row]];
            cell.textLabel.font = font;
        }else{
            cell = nil;
            cell = [tableView dequeueReusableCellWithIdentifier:@"withInputCell"];
        }
    }else{
        cell = nil;
        cell = [tableView dequeueReusableCellWithIdentifier:@"reuseCell"];
        cell.textLabel.text = [_invoiceList objectAtIndex:indexPath.row][@"name"];
        cell.textLabel.font = font;
    }
    
    return cell;
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        switch (indexPath.row) {
            case 2:
                _invoiceType = @"2";
                _typeTitle = @"公司";
                break;
            case 1:
                _invoiceType = @"1";
                _typeTitle = @"个人";
                break;
            default:
                _invoiceType = @"3";
                _typeTitle = @"不开发票";
                UITableViewCell *oldCell = [tableView cellForRowAtIndexPath:_lastIndex1];
                oldCell.accessoryType = UITableViewCellAccessoryNone;
                if (_lastIndex1.row != indexPath.row) {
                    [tableView deselectRowAtIndexPath:self.lastIndex1 animated:YES];
                }
                
                break;
        }
            UITableViewCell *oldCell = [tableView cellForRowAtIndexPath:_lastIndex0];
            oldCell.accessoryType = UITableViewCellAccessoryNone;
            UITableViewCell *newCell = [tableView cellForRowAtIndexPath:indexPath];
            newCell.accessoryType = UITableViewCellAccessoryCheckmark;
        if (indexPath.row == 2) {
            UITextField *txtField = (UITextField*)[newCell viewWithTag:1000];
            [txtField setUserInteractionEnabled:YES];
            [txtField becomeFirstResponder];
        }

        self.lastIndex0 = indexPath;
    }
    if (indexPath.section == 1 && ![_invoiceType isEqualToString:@"3"]) {
        _invoiceItem = [NSString stringWithFormat:@"%@",[_invoiceList objectAtIndex:indexPath.row][@"id"]];
        _itemTitle = [NSString stringWithFormat:@"%@",[_invoiceList objectAtIndex:indexPath.row][@"name"]];
        //发票明细(@"%@",_invoiceItem);
        UITableViewCell *oldCell = [tableView cellForRowAtIndexPath:_lastIndex1];
        oldCell.accessoryType = UITableViewCellAccessoryNone;
        UITableViewCell *newCell = [tableView cellForRowAtIndexPath:indexPath];
        newCell.accessoryType = UITableViewCellAccessoryCheckmark;
        self.lastIndex1 = indexPath;
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
   _invoiceInfo = [NSMutableDictionary dictionaryWithObjectsAndKeys:_invoiceType,@"invoiceType",_typeTitle, @"typeTitle",_invoiceTitle,@"invocieTitle",_invoiceItem, @"invocieItem",_itemTitle, @"itemTitle",nil];

}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    _invoiceTitle = textField.text;
    [textField resignFirstResponder];
    return true;
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    _invoiceTitle = textField.text;
    [_invoiceInfo setValue:_invoiceTitle forKey:@"invocieTitle"];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
